<?php
/**
 * +----------------------------------------------------------------------
 * | Copyright © Sogu Technologies Co. Ltd 2018-2050 All rights reserved.
 * +----------------------------------------------------------------------
 * | File name: WithholdingController.php
 * +----------------------------------------------------------------------
 * | Author: lijiafei
 * +----------------------------------------------------------------------
 * | Description:代扣逻辑
 * +----------------------------------------------------------------------
 * | Others: 其他内容的说明
 * +----------------------------------------------------------------------
 * | History:
 * +----------------------------------------------------------------------
 * | 1.Date: 2019/3/1 Author: lijiafei Modification: 创建
 * +----------------------------------------------------------------------
 */

namespace App\Http\Controllers\Collection;
use App\Constant\RepayConstant;
use App\Events\CollectionReceiptEvent;
use App\Events\WithHoldEvent;
use App\Http\Requests\Collection\BaseRequest;
use App\Jobs\RepayCommonJobQueue;
use App\Jobs\RepayJobQueue;
use App\Jobs\RepayMonthJobQueue;
use App\Models\CollectionApiRequest;
use App\Models\RepayRecordCommon;
use App\Models\RepayRecordMoney;
use App\Models\RepayRecordMonth;
use App\Models\RepaySummary;
use App\Models\RepayRecord;
use Illuminate\Support\Facades\Log;

class WithholdingController extends BaseController
{

//    public function withholding()
//    {
//        $data = $this->pubData;
//        $loan_id = $data['caseCode'];
//        $summaryInfo = RepaySummary::where('loan_id', $loan_id)->first();
//        if (!$summaryInfo) {
//            $returnData['result'] = CollectionApiRequest::RESPONSE_OTHER_ERROR;
//            $returnData['msg'] = '代扣数据不存在';
//            return collectionResp($returnData);
//        }
//
//        if ($summaryInfo->status == RepaySummary::STATUS_TWO) {
//            $returnData['result'] = CollectionApiRequest::RESPONSE_OTHER_ERROR;
//            $returnData['msg'] = '当前还款数据已还清';
//            return collectionResp($returnData);
//        }
//
//        if($data['type'] == CollectionApiRequest::WITHHOLDING_ONE){//todo 还一期
//            $result = $summaryInfo->verifySingleRepay($data)->original->resultData;// 验证
//            $result=json_decode(json_encode($result),1);
//            if (isset($result['status']) && $result['status']) {
//                //调用队列
//                $jobResult = RepaySummary::setCurrentRepayJob($result['result']);
//                if (isset($jobResult['flag']) && $jobResult['flag']) {
//                    $returnData['result'] = CollectionApiRequest::RESPONSE_OK;
//                    $returnData['msg'] = $jobResult['msg'];
//                    RepayRecord::where('summary_id',$summaryInfo->id)->
//                    whereIn('period',explode(',',$this->pubData['period']))
//                        ->update(['repay_type'=>\App\Models\RepayRecord::REPAY_TYPE_WITHHOLDING]);
//                } else {
//                    $returnData['result'] = CollectionApiRequest::RESPONSE_OTHER_ERROR;
//                    $returnData['msg'] = $jobResult['msg'];
//                }
//                return collectionResp($returnData);
//
//            } else {
//                return collectionResp($result);
//            }
//        } elseif ($data['type'] == CollectionApiRequest::WITHHOLDING_TWO) {//todo 还多期
//            if (empty($data['period'])) {
//                $returnData['result'] = CollectionApiRequest::RESPONSE_OTHER_ERROR;
//                $returnData['msg'] = '数据不正确';
//                return collectionResp($returnData);
//            }
//            $result = $summaryInfo->verifyMultipleRepay($data)->original->resultData;// 数据验证
//            $result=json_decode(json_encode($result),1);
//            if($result['status']){
//                if(empty($result['result'])){
//                    $returnData['result'] = CollectionApiRequest::RESPONSE_OTHER_ERROR;
//                    $returnData['msg'] = '没有对应代扣数据';
//                    return collectionResp($returnData);
//                }
//                foreach ($result['result'] as $repayReCord) {
//
//                    $jobResult = RepaySummary::setCurrentRepayJob(RepayRecord::find($repayReCord['id']));
//                }
//                if (isset($jobResult['flag']) && $jobResult['flag']) {
//                    $returnData['result'] = CollectionApiRequest::RESPONSE_OK;
//                    $returnData['msg'] = $jobResult['msg'];
//                    RepayRecord::where('summary_id',$summaryInfo->id)->
//                    whereIn('period',explode(',',$this->pubData['period']))
//                        ->update(['repay_type'=>\App\Models\RepayRecord::REPAY_TYPE_WITHHOLDING]);
//                } else {
//                    $returnData['result'] = CollectionApiRequest::RESPONSE_OTHER_ERROR;
//                    $returnData['msg'] = $jobResult['msg'];
//                }
//                return collectionResp($returnData);
//            }else{
//                return collectionResp($result);
//            }
//
//        }elseif($data['type'] == CollectionApiRequest::WITHHOLDING_ZERO) {//todo  全部结清
//            $result = $summaryInfo->verifyAllRepay($data)->original->resultData;// 验证
//            $result=json_decode(json_encode($result),1);
//            if (isset($result['status']) && $result['status']) {
//                $repayReCord=RepayRecord::find($result['result']['id']);
//                $jobResult = RepaySummary::setAllRepayJob($repayReCord, RepayRecord::REPAY_TYPE_REPAYMENT);
//                if ($jobResult['flag'] == true) {
//                    $returnData['result'] = CollectionApiRequest::RESPONSE_OK;
//                    RepayRecord::where('summary_id',$summaryInfo->id)->
//                    whereIn('period',explode(',',$this->pubData['period']))
//                        ->update(['repay_type'=>\App\Models\RepayRecord::REPAY_TYPE_WITHHOLDING]);
//                } else {
//                    $returnData['result'] = CollectionApiRequest::RESPONSE_OTHER_ERROR;
//                }
//                $returnData['msg'] = $jobResult['msg'];
//                return collectionResp($returnData);
//            } else {
//                return collectionResp($result);
//            }
//        }
//
//
//
//
//    }

   /*
    * 代扣
    * @param caseCode    loan_id
    * @param period      当前期数
    * @param type        1还1期  2 还多期 0全部结清
    * @param applyNumber  申请流水号 作为唯一标识
    */

    public function withholding()
    {
        $data = $this->pubData;
        $returnData=[];
        if(strstr($data['period'],',')){
            $returnData['result'] = CollectionApiRequest::RESPONSE_OTHER_ERROR;
            $returnData['msg'] = '暂时不支持多期';
            return $returnData;
        }
        $period=[];
        if(isset($data['type'])){
            //还1期
            $period[]=$data['period'];
        }
//        elseif ($data['type']==2){
//            //还多期
//            $period=explode(',',$data['period']);
//        }else{
//            //还清
//            $period_get=RepaySummary::leftJoin('repay_records as r', 'repay_summaries.id', '=', 'r.summary_id')
//                ->where('repay_summaries.loan_id',$data['caseCode'])
//                ->whereIn('r.status',[RepayRecord::STATUS_ONE,RepayRecord::STATUS_THREE])->select('r.period')->get();
//            $period=$period_get->pluck('period')->toArray();
//        }

        $info=RepaySummary::leftJoin('repay_records as a', 'repay_summaries.id', '=', 'a.summary_id')
            ->leftJoin('repay_record_months as b', 'a.id', '=', 'b.record_id')
            ->leftJoin('repay_record_moneys as c', 'a.id', '=', 'c.record_id')
            ->leftJoin('repay_record_commons as d', 'a.id', '=', 'd.record_id')
            ->where('repay_summaries.loan_id',$data['caseCode'])
            ->whereIn('a.period', $period)
            ->where('a.status','<>',RepayRecord::STATUS_FOUR)
            ->select([
                'repay_summaries.uid as uid',
                'repay_summaries.loan_id as loan_id',
                //a是repay_record表
                'a.id as record_id',
                'a.period as record_period',
                'a.status as record_status',
                //b是months表
                'b.status as month_status',
                'b.period as month_period',
                //c是 moneys表
                'c.status as money_status',
                'c.summary_id as summary_id',
                'c.period as money_period',
                //d是commons表
                'd.status as common_status',
                'd.period as common_period'
            ])
            ->get();
        if(count($info)==0){
            $returnData['result'] = CollectionApiRequest::RESPONSE_OTHER_ERROR;
            $returnData['msg'] = '代扣数据不存在';
            return collectionResp($returnData);
        }
        $flag=false;
        foreach($info as $k=>$v){
            $repayRecord=RepayRecord::find($v['record_id']);
            if($v['record_status']==RepayRecord::STATUS_FOUR) {
                //已经还款完成--直接跳过
                continue;
            }elseif($v['record_status']==RepayRecord::STATUS_TWO){
                //当期正在处理中，不能往下进行 return
                $returnData['result'] = CollectionApiRequest::RESPONSE_OTHER_ERROR;
                $returnData['msg'] = $v['record_period'].'期正在还款中';
                return $returnData;
            }else{
                //可以正常还款 一期一期有序进行
                //判断是否需要走京东裸扣
                $flag=RepaySummary::isBuckle($repayRecord,RepayRecord::REPAY_TYPE_MANUAL);
                if($flag != 1){
                    return $flag;
                }
                if($v['money_status'] == RepayRecordMoney::STATUS_ONE || $v['money_status'] == RepayRecordMoney::STATUS_THREE)
                {
                    //资方队列
                    $res = RepayJobQueue::dispatch($v['record_id']);
                    if($res){
                        RepaySummary::setRepayStatus($v['record_id'],$v['uid'],$v['summary_id'],$v['money_period'],'money',RepayRecord::REPAY_TYPE_MANUAL);
                    }
                    $flag=true;
                    $returnData['msg'] = '第'.$v['record_period'].'期正在还款中,请等待';
                }elseif ($v['money_status'] == RepayRecordMoney::STATUS_FOUR){

                    if($v['month_status'] == RepayRecordMonth::STATUS_ONE || $v['month_status'] == RepayRecordMonth::STATUS_THREE){
                        //月保费队列
                        $res = RepayMonthJobQueue::dispatch($v['record_id']);
                        if($res){
                            RepaySummary::setRepayStatus($v['record_id'],$v['uid'],$v['summary_id'],$v['month_period'],'month',RepayRecord::REPAY_TYPE_MANUAL);
                        }
                        $returnData['msg'] = '正在还款中,请等待';
                    }elseif($v['month_status'] == RepayRecordMonth::STATUS_FOUR){
                        if($v['common_status'] == RepayRecordCommon::STATUS_THREE || $v['common_status'] == RepayRecordCommon::STATUS_ONE)
                        {
                            //公共平台队列
                            $res = RepayCommonJobQueue::dispatch($v['record_id']);
                            if($res){
                                RepaySummary::setRepayStatus($v['record_id'],$v['uid'],$v['summary_id'],$v['common_period'],'common',RepayRecord::REPAY_TYPE_MANUAL);
                            }

                        }elseif($v['common_status'] == RepayRecordCommon::STATUS_FOUR){
                            $returnData['flag'] = false;
                            $returnData['msg'] = '当前期已经还款成功';
                            return $returnData;
                        }
                    }
                    $flag=true;
                }
                if ($flag) {
                    $returnData['result'] = CollectionApiRequest::RESPONSE_OK;
                    RepayRecord::where('summary_id',$v['summary_id'])->
                    where('period',$v['record_period'])
                        ->update(['repay_type'=>RepayRecord::REPAY_TYPE_WITHHOLDING]);
                    RepayRecordMoney::where('summary_id',$v['summary_id'])->
                    where('period',$v['record_period'])
                        ->update(['repay_type'=>RepayRecord::REPAY_TYPE_WITHHOLDING]);
                    RepayRecordMonth::where('summary_id',$v['summary_id'])->
                    where('period',$v['record_period'])
                        ->update(['repay_type'=>RepayRecord::REPAY_TYPE_WITHHOLDING]);
                    RepayRecordCommon::where('summary_id',$v['summary_id'])->
                    where('period',$v['record_period'])
                        ->update(['repay_type'=>RepayRecord::REPAY_TYPE_WITHHOLDING]);
                } else {
                    $returnData['result'] = CollectionApiRequest::RESPONSE_OTHER_ERROR;
                }
            }
            RepayRecord::where('id',$v['record_id'])->where('period',$v['record_period'])->update(['apply_number'=>$data['applyNumber']]);
            event(new WithHoldEvent(['caseCode'=>$v['loan_id'],'type'=>RepayConstant::COLLECTION_BACK_TYPE_ONE,'applyNumber'=>$data['applyNumber'],'state'=>RepayRecord::STATUS_FOUR]));
        }
        return collectionResp($returnData);
    }

}